/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.centrodata.controller;

import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.Validator;
import br.com.caelum.vraptor.validator.Validations;
import br.com.centrodata.dao.ProjectDao;
import br.com.centrodata.model.Project;

/**
 *
 * @author João Fernandes Lima Neto
 */
@Resource
public class ProjectController implements GenericController<Project> {

    private Result     result;
    private Validator  validator;
    private ProjectDao dao;

    public ProjectController(Result result, Validator validator, ProjectDao dao) {
        this.result = result;
        this.validator = validator;
        this.dao = dao;
    }

    @Path("/project/index")
    @Get
    @Override
    public void index() {
        result.include("projects", dao.search());
    }

    @Path("/project/new")
    @Get
    @Override
    public void form() {
    }

    @Path("/project/{project.id}")
    @Get
    @Override
    public void form(Project project) {
        result.include("project", dao.search(project.getId()));
    }

    @Path("/project/delete/{project.id}")
    @Get
    @Override
    public void delete(Project project) {
        try{
            dao.del(project);
            result.include("notice", "Registro deletado com sucesso");
            result.redirectTo(this).index();
        }catch(Exception e){
            result.include("error", "Ocorreu um erro ao tentar deletar o registro");
            result.redirectTo(this).index();
        }
    }

    @Path("/project/save")
    @Post
    @Override
    public void save(Project project) {
        
        boolean isEdit = project.getId() > 0;
        
        /* se estiver Editando */
        if(isEdit){
            this.dao.update(project);
            result.include("notice", "Usuário [" + project.getDescricao() + "] atualizado com sucesso.");
        }else{
            this.dao.add(project);
            result.include("notice", "Usuário [" + project.getDescricao() + "] inserido com sucesso.");
        }
        result.forwardTo(this).index();
    }
    
}
